package run.siyuan.jdk.漫画算法.队列;

/**
 * @ClassName LinkedQueue
 * @Description TODO
 * @Author siyuan
 * @Date 2023/4/8 10:37
 */
public class LinkedQueue {

    private Node head = new Node();

    private Node last = new Node();

    private int size = 0;

    public static void main(String[] args) {
        LinkedQueue queue = new LinkedQueue();
        queue.enqueue(10);
        queue.enqueue(11);
        queue.enqueue(12);
        queue.enqueue(13);
        queue.enqueue(14);
        queue.enqueue(15);
        queue.show();
        queue.dequeue();
        queue.dequeue();
        queue.dequeue();
        queue.dequeue();
        queue.show();


    }

    /**
     * 入队
     *
     * @param element
     */
    public void enqueue(int element) {
        Node insertNode = new Node(element);
        if (size == 0) {
            // 第一个元素构建一个双向链表
            insertNode.next = last;
            insertNode.pre = head;

            last.pre = insertNode;
            last.next = head;

            head.next = insertNode;
            head.pre = last;
        } else if (size > 0) {
            // 非第一个元素，插入后修改节点指向
            Node node = last.pre;

            insertNode.pre = node;
            insertNode.next = last;

            node.next = insertNode;
            last.pre = insertNode;
        }
        size++;

    }

    /**
     * 出队
     */
    public void dequeue() {
        Node next = head.next;
        head.next = next.next;
        size--;
    }

    /**
     * 打印
     */
    public void show() {
        Node node = head.next;
        for (int i = 0; i < size; i++) {
            System.out.printf("%d\t%d\n",i,node.data);
            node = node.next;
        }
    }

    class Node {
        private Node pre;
        private int data;
        private Node next;

        public Node() {
        }

        public Node(Node pre, int data, Node next) {
            this.pre = pre;
            this.data = data;
            this.next = next;
        }

        public Node(int data) {
            this.data = data;
        }

        public Node(Node pre, int data) {
            this.pre = pre;
            this.data = data;
        }
    }
}
